package com.bsb.biz.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bsb.base.common.config.Area;
import com.bsb.base.common.config.Const;
import com.bsb.base.common.config.Global;
import com.bsb.base.common.util.DateUtils;
import com.bsb.base.common.util.IdGen;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.common.util.UmengPushUtil;
import com.bsb.base.model.BsbCategory;
import com.bsb.base.model.BsbExpertQu;
import com.bsb.base.model.BsbExpertQuExample;
import com.bsb.base.model.BsbExpertVoice;
import com.bsb.base.model.BsbExpertVoiceExample;
import com.bsb.base.model.BsbFirm;
import com.bsb.base.model.BsbFirmExample;
import com.bsb.base.model.BsbUserExample;
import com.bsb.base.model.SysUser;
import com.bsb.base.model.BsbExpertVoiceExample.Criteria;
import com.bsb.base.model.BsbUser;
import com.bsb.base.model.Expert;
import com.bsb.base.model.ExpertQuUserFirm;
import com.bsb.biz.service.BsbCategoryService;
import com.bsb.biz.service.BsbExpertQuService;
import com.bsb.biz.service.BsbExpertVoiceService;
import com.bsb.biz.service.BsbFirmService;
import com.bsb.biz.service.BsbUserService;
import com.bsb.biz.shiro.UserUtils;

import push.AndroidNotification;
import push.PushClient;
import push.android.AndroidUnicast;
import push.ios.IOSCustomizedcast;

@Controller
@RequestMapping("/bsbExpertQu")
public class BsbExpertQuController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/bsbExpertQu/list.do";
	
	@Resource
	private BsbExpertQuService bsbExpertQuService;
	@Resource
	private BsbCategoryService bsbCategoryService;
	
	@Resource
	private BsbUserService bsbUserService;
	@Resource
	private BsbExpertVoiceService bsbExpertVoiceService;
	
	@Resource
	private BsbFirmService BsbFirmService;
	
	@RequiresPermissions("bsbExpertQu:view")
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(
			Model model,@RequestParam Map<String, Object> params,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		BsbExpertQuExample bsbExpertQuExample = new BsbExpertQuExample();
		
		String name = (String) params.get("name");
		String question = (String) params.get("question");
		String quid = (String) params.get("quid");
		String delflag = (String) params.get("delflag");
		String status = (String) params.get("status");
		String trade = (String) params.get("trade");
		String tax = (String) params.get("tax");
		String topic = (String) params.get("topic");
		String firm = (String) params.get("firm");
		String start = (String) params.get("start");
		Date startDate = DateUtils.parseDate(start);
		String end = (String) params.get("end");
		Date endDate = DateUtils.parseDate(end);
		com.bsb.base.model.BsbExpertQuExample.Criteria criteria = bsbExpertQuExample.createCriteria();
		if(StringUtils.isNotEmpty(status)){
			criteria.andStatusEqualTo(status);
		}
		if(startDate!=null){
			criteria.andCreateDateGreaterThanOrEqualTo(startDate);
		}
		if(endDate!=null){
			endDate=DateUtils.addDays(endDate, 1);
			criteria.andCreateDateLessThanOrEqualTo(endDate);
		}
		if(StringUtils.isNotBlank(question)){
			criteria.andQuestionLike("%"+question+"%");
		}
		if(StringUtils.isNotBlank(quid)){
			criteria.andUuidLike("%"+quid+"%");
		}
		
		if(StringUtils.isNotBlank(trade)){
			criteria.andTradeEqualTo(trade);
		}
		
		if(StringUtils.isNotBlank(tax)){
			criteria.andTaxEqualTo(tax);
		}
		if(StringUtils.isNotBlank(topic)){
			criteria.andTopicEqualTo(topic);
		}
		
		if(StringUtils.isNotBlank(delflag)){
			criteria.andDelFlagEqualTo(delflag);
		}
		BsbUserExample bsbUserExample=null; 
		if(StringUtils.isNotBlank(name)){
			bsbUserExample= new BsbUserExample();
			com.bsb.base.model.BsbUserExample.Criteria criteria2 = bsbUserExample.createCriteria();
			criteria2.andNameLike("%"+name+"%");
		}
		SysUser currentUser = UserUtils.currentUser();
		Long firmId = currentUser.getFirmId();
		if(firmId==null){
			model.addAttribute("msg", "账号异常请联系管理员！");
			return "/BsbExpertQu/list";
		}
		BsbFirmExample bsbFirmExample=null; 
		
		
		if(firmId!=10000){
			bsbFirmExample= new BsbFirmExample();
			com.bsb.base.model.BsbFirmExample.Criteria criteria3 = bsbFirmExample.createCriteria();
			criteria3.andAccountEqualTo(firmId.intValue());
			criteria3.andDelFlagEqualTo(Global.SHOW);
			if(StringUtils.isNotBlank(firm)){
				
				criteria3.andNameLike("%"+firm+"%");
			}
		}else {
			
			if(StringUtils.isNotBlank(firm)){
				bsbFirmExample= new BsbFirmExample();
				com.bsb.base.model.BsbFirmExample.Criteria criteria3 = bsbFirmExample.createCriteria();
				criteria3.andNameLike("%"+firm+"%");
			}
		}
		int totalCount =bsbExpertQuService.getCountExpertQuUserFirm(bsbExpertQuExample, bsbUserExample, bsbFirmExample);
		//= bsbExpertQuService.countBsbExpertQu(bsbExpertQuExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		
		
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
			if(maxPageNum==0){
				pageNum=1;
			}
		}
		bsbExpertQuExample.setPageIndex((pageNum - 1) * pageSize);
		bsbExpertQuExample.setPageSize(pageSize);
		
		//
		

		bsbExpertQuExample.setOrderByClause("bsb_expert_qu.createDate desc");
		List<ExpertQuUserFirm> expertQuUserFirms = bsbExpertQuService.getExpertQuUserFirms(bsbExpertQuExample, bsbUserExample, bsbFirmExample);
		//List<BsbExpertQu> bsbExpertQus = bsbExpertQuService.getPageBsbExpertQu(bsbExpertQuExample);
		
		for (ExpertQuUserFirm bsbExpertQu : expertQuUserFirms) {
			String tradeName = bsbCategoryService.getCategoryName(bsbExpertQu.getTrade());
			String taxName = bsbCategoryService.getCategoryName(bsbExpertQu.getTax());
			String topicName = bsbCategoryService.getCategoryName(bsbExpertQu.getTopic());
			bsbExpertQu.setTrade(tradeName);
			bsbExpertQu.setTax(taxName);
			bsbExpertQu.setTopic(topicName);
		}
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("name", name);
		model.addAttribute("question", question);
		model.addAttribute("quid", quid);
		model.addAttribute("delflag", delflag);
		model.addAttribute("trade", trade);
		
		model.addAttribute("tax", tax);
		model.addAttribute("topic", topic);
		model.addAttribute("firmId", firmId);
		model.addAttribute("firm", firm);
		model.addAttribute("status", status);
		model.addAttribute("start", start);
		model.addAttribute("end", end);
		model.addAttribute("bsbExpertQus", expertQuUserFirms);
		List<BsbCategory> trades = bsbCategoryService.childList("1");//行业
		List<BsbCategory> taxs = bsbCategoryService.childList("2");//税种
		List<BsbCategory> topics = bsbCategoryService.childList("3");//专题
		model.addAttribute("trades", trades);
		model.addAttribute("taxs", taxs);
		model.addAttribute("topics", topics);
		
		
		return "/BsbExpertQu/list";
	}
	
	
	
	@RequiresPermissions("bsbExpertQu:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model) {
		List<BsbCategory> trades = bsbCategoryService.childList("1");//行业
		List<BsbCategory> taxs = bsbCategoryService.childList("2");//税种
		List<BsbCategory> topics = bsbCategoryService.childList("3");//专题
		List<Area> areaList = Area.getList();
		List<Expert> expertList = bsbUserService.expertList();
		model.addAttribute("trades", trades);
		model.addAttribute("taxs", taxs);
		model.addAttribute("topics", topics);
		model.addAttribute("areas", areaList);
		model.addAttribute("experts", expertList);
		return "/BsbExpertQu/add";
	}

	@RequiresPermissions("bsbExpertQu:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public Object add(Model model,
			@RequestParam(value = "areatax", required = false) String areatax,
			@RequestParam(value = "audio", required = false) String audio,
			@RequestParam(value = "duration", required = false) Long duration,
			@RequestParam(value = "audiotxt", required = false) String audiotxt,
			@ModelAttribute("bsbExpertQu") BsbExpertQu bsbExpertQu) {
		String uuid = IdGen.uuid();
		bsbExpertQu.setUuid(uuid);
		String phone = bsbExpertQu.getUserId();
		BsbUser userByPhone = bsbUserService.getUserByPhone(phone);
		if(StringUtils.isNotEmpty(areatax)){
			bsbExpertQu.setTax(areatax);
		}
		String areaId = bsbExpertQu.getAreaId();
		if(StringUtils.isEmpty(areaId)){
			bsbExpertQu.setAreaId(null);
		}
		bsbExpertQu.setCreateDate(new Date());
		bsbExpertQu.setUserId(userByPhone.getUuid());
		
		BsbExpertVoice voice = new BsbExpertVoice();
		voice.setUuid(uuid);
		voice.setCreateDate(new Date());
		voice.setName(audio);
		voice.setExpertId(uuid);
		voice.setContent(audiotxt);
		voice.setVoiceTime(duration);
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			bsbExpertQuService.addExpertQuVoice(bsbExpertQu,voice);
			map.put("status", true);
			map.put("msg", "添加成功");
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", false);
			map.put("msg", "系统繁忙");
			return map;
		}
	}
	
	@RequiresPermissions("bsbExpertQu:delete")
	@RequestMapping(value = "/{uuid}/delete", method = RequestMethod.GET)
	public String del(Model model,
			@PathVariable("uuid") String uuid) {
		bsbExpertQuService.delBsbExpertQuByUuid(uuid);
		return redirect;
	}
	@RequiresPermissions("bsbExpertQu:delete")
	@RequestMapping(value = "/{uuid}/hide", method = RequestMethod.GET)
	public String hide(Model model,RedirectAttributes redirectAttributes,
			HttpServletRequest request,
			@PathVariable("uuid") String uuid) {
		BsbExpertQu bsbExpertQu = new BsbExpertQu();
		bsbExpertQu.setUuid(uuid);
		bsbExpertQu.setDelFlag(Global.HIDE);
		bsbExpertQuService.updateBsbExpertQu(bsbExpertQu);
		redirectAttributes.addFlashAttribute("msg", "隐藏成功");
		String queryString = request.getQueryString();
		if(StringUtils.isEmpty(queryString)){
			queryString = "";
		}
		return redirect + "?" +queryString;
	}
	@RequiresPermissions("bsbExpertQu:delete")
	@RequestMapping(value = "/{uuid}/show", method = RequestMethod.GET)
	public String show(Model model,RedirectAttributes redirectAttributes,
			HttpServletRequest request,
			@PathVariable("uuid") String uuid) {
		BsbExpertQu bsbExpertQu = new BsbExpertQu();
		bsbExpertQu.setUuid(uuid);
		bsbExpertQu.setDelFlag(Global.SHOW);
		bsbExpertQuService.updateBsbExpertQu(bsbExpertQu);
		redirectAttributes.addFlashAttribute("msg", "显示成功");
		String queryString = request.getQueryString();
		if(StringUtils.isEmpty(queryString)){
			queryString = "";
		}
		return redirect + "?" +queryString;
	}
	
	@RequiresPermissions("bsbExpertQu:check")
	@RequestMapping(value = "/{uuid}/check", method = RequestMethod.GET)
	public String toCheck(Model model,RedirectAttributes redirectAttributes,
			HttpServletRequest request,
			@PathVariable("uuid") String uuid) {
		BsbExpertQu bsbExpertQu = bsbExpertQuService.getBsbExpertQuByUuid(uuid);
		if(null == bsbExpertQu){
			return "error/400";
		}
		String status = bsbExpertQu.getStatus();
		if(!Const.VOICE_INIT.equals(status) && !Const.VOICE_REPAIR_INIT.equals(status)){
			redirectAttributes.addFlashAttribute("msg", "该条数据已经审核过不能再次审核");
			return redirect;
		}
		String trade = bsbCategoryService.getCategoryName(bsbExpertQu.getTrade());
		String tax = bsbCategoryService.getCategoryName(bsbExpertQu.getTax());
		String topic = bsbCategoryService.getCategoryName(bsbExpertQu.getTopic());
		bsbExpertQu.setTrade(trade);
		bsbExpertQu.setTax(tax);
		bsbExpertQu.setTopic(topic);
		String userId = bsbUserService.getUserNameById(bsbExpertQu.getUserId());
		bsbExpertQu.setUserId(userId);
		List<BsbExpertVoice> voicelist = getVoiceList(uuid);
		model.addAttribute("voicelist", voicelist);
		model.addAttribute("bsbExpertQu", bsbExpertQu);
		return "/BsbExpertQu/check";
	}

	
	@RequiresPermissions("bsbExpertQu:update")
	@RequestMapping(value = "/{uuid}/update", method = RequestMethod.GET)
	public String toEdit(Model model,RedirectAttributes redirectAttributes,
			HttpServletRequest request,
			@PathVariable("uuid") String uuid) {
		BsbExpertQu bsbExpertQu = bsbExpertQuService.getBsbExpertQuByUuid(uuid);
		if(null == bsbExpertQu){
			return "error/400";
		}
		String userId = bsbUserService.getUserNameById(bsbExpertQu.getUserId());
		List<BsbCategory> trades = bsbCategoryService.childList("1");//行业
		List<BsbCategory> taxs = bsbCategoryService.childList("2");//税种
		List<BsbCategory> topics = bsbCategoryService.childList("3");//专题
		List<Area> areaList = Area.getList();
		model.addAttribute("trades", trades);
		model.addAttribute("taxs", taxs);
		model.addAttribute("topics", topics);
		model.addAttribute("areas", areaList);
		bsbExpertQu.setUserId(userId);
		model.addAttribute("bsbExpertQu", bsbExpertQu);
		List<BsbExpertVoice> voicelist = getVoiceList(uuid);
		model.addAttribute("voicelist", voicelist);
		String queryString = request.getQueryString();
		model.addAttribute("queryString", queryString);
		return "/BsbExpertQu/edit";
	}
	
	@RequiresPermissions("bsbExpertQu:update")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String edit(Model model,RedirectAttributes redirectAttributes,
			@RequestParam(value = "areatax", required = false) String areatax,
			@RequestParam(value = "queryString", required = false) String queryString,
			@ModelAttribute("bsbExpertQu") BsbExpertQu bsbExpertQu) {
			SysUser currentUser = UserUtils.currentUser();
			Long firmId = currentUser.getFirmId();
			if(firmId!=10000){
			redirectAttributes.addFlashAttribute("msg", "你没有权限！");
			return redirect;
			}
		String uuid = bsbExpertQu.getUuid();
		String areaId = bsbExpertQu.getAreaId();
		BsbExpertQu qu = new BsbExpertQu();
		qu.setUuid(uuid);
		if(StringUtils.isEmpty(areaId)){
			qu.setAreaId("");
			qu.setTax("");
			String trade = bsbExpertQu.getTrade();
			if(StringUtils.isNotEmpty(trade)){
				qu.setTrade(trade);
			}
			String tax = bsbExpertQu.getTax();
			if(StringUtils.isNotEmpty(tax)){
				qu.setTax(tax);
			}
			String topic = bsbExpertQu.getTopic();
			if(StringUtils.isNotEmpty(topic)){
				qu.setTopic(topic);
			}
		}else{
			qu.setAreaId(areaId);
			qu.setTrade("");
			qu.setTopic("");
			qu.setTax("");
			if(StringUtils.isNotEmpty(areatax)){
				qu.setTax(areatax);
			}
		}
		
		
		if(StringUtils.isEmpty(queryString)){
			queryString = "";
		}
		bsbExpertQuService.updateBsbExpertQu(qu);
		return redirect + "?" +queryString;
	}


	private List<BsbExpertVoice> getVoiceList(String uuid) {
		BsbExpertVoiceExample example = new BsbExpertVoiceExample();
		Criteria criteria = example.createCriteria();
		criteria.andExpertIdEqualTo(uuid);
		example.setOrderByClause("createDate DESC");
		List<BsbExpertVoice> voicelist = bsbExpertVoiceService.selectByExample(example );
		return voicelist;
	}

	@RequiresPermissions("bsbExpertQu:check") 
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	public String ckeck(Model model,RedirectAttributes redirectAttributes,
			@ModelAttribute("bsbExpertQu") BsbExpertQu bsbExpertQu){
		String uuid = bsbExpertQu.getUuid();
		SysUser currentUser = UserUtils.currentUser();
		Long firmId = currentUser.getFirmId();
		if(firmId!=10000){
			redirectAttributes.addFlashAttribute("msg", "你没有权限！");
			return redirect;
		}
		//判断库中数据的状态是否可以审核
		BsbExpertQu bsbExpertQuByUuid = bsbExpertQuService.getBsbExpertQuByUuid(uuid);
		String status = bsbExpertQuByUuid.getStatus();
		if(!Const.VOICE_INIT.equals(status) && !Const.VOICE_REPAIR_INIT.equals(status)){
			redirectAttributes.addFlashAttribute("msg", "该条数据已经审核过不能再次审核");
			return redirect;
		}
	
		//根据接收到的状态和库中现在的状态来决定审核后的状态
		String status2 = bsbExpertQu.getStatus();
		String title = "";
		String type = "";
		String userId = bsbExpertQuByUuid.getUserId();
		if(Const.CHECKYES.equals(status2)){
			if(Const.VOICE_INIT.equals(status)){
				bsbExpertQu.setStatus(Const.VOICE_PASS);
			}else if(Const.VOICE_REPAIR_INIT.equals(status)){
				bsbExpertQu.setStatus(Const.VOICE_REPAIR_PASS);
			}
			title = "恭喜您，您的录音审核已通过。";
			type = "2";
		}else if(Const.CHECKNO.equals(status2)){
			if(Const.VOICE_INIT.equals(status)){
				bsbExpertQu.setStatus(Const.VOICE_NOPASS);
			}else if(Const.VOICE_REPAIR_INIT.equals(status)){
				bsbExpertQu.setStatus(Const.VOICE_REPAIR_NOPASS);
			}
			title = "很抱歉，您的录音审核未通过，请查看。";
			type = "3";
		}else{
			return "error/400";
		}
		Map<String , String> map = new HashMap<String , String>();
		map.put("type", type);
		try {
			UmengPushUtil.sendAndroidCustomizedcast(title, userId, map);
			UmengPushUtil.sendIOSCustomizedcast(title, userId, map);
		} catch (Exception e) {
		}
		bsbExpertQu.setUpdateBy((String)SecurityUtils.getSubject().getPrincipal());
		bsbExpertQu.setUpdateDate(new Date());
		bsbExpertQuService.updateBsbExpertQu(bsbExpertQu);
		redirectAttributes.addFlashAttribute("msg", "审核成功");
		return redirect;
	}
	
	@RequiresPermissions("bsbExpertQu:price")
	@RequestMapping(value = "/{uuid}/price", method = RequestMethod.POST)
	@ResponseBody
	public boolean price(Model model,RedirectAttributes redirectAttributes,
			@PathVariable("uuid") String uuid,String price) {
		try {
			SysUser currentUser = UserUtils.currentUser();
			Long firmId = currentUser.getFirmId();
			if(firmId!=10000){
			redirectAttributes.addFlashAttribute("msg", "你没有权限！");
			return false;
			}
			if(StringUtils.isEmpty(price)){
				return false;
			}
			double price1 = Double.valueOf(price);
			if(price1<0){
				return false;
			}
			BsbExpertQu bsbExpertQu = new BsbExpertQu();
			bsbExpertQu.setUuid(uuid);
			bsbExpertQu.setQuPrice(price1);
			bsbExpertQu.setUpdateBy((String)SecurityUtils.getSubject().getPrincipal());
			bsbExpertQu.setUpdateDate(new Date());
			bsbExpertQuService.updateBsbExpertQu(bsbExpertQu);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	@RequiresPermissions("bsbExpertQu:view")
	@RequestMapping(value = "/{uuid}/view", method = RequestMethod.GET)
	public String view(Model model,
			@PathVariable("uuid") String uuid) {
		BsbExpertQu bsbExpertQu = bsbExpertQuService.getBsbExpertQuByUuid(uuid);
		model.addAttribute("bsbExpertQu", bsbExpertQu);
		String trade = bsbCategoryService.getCategoryName(bsbExpertQu.getTrade());
		String tax = bsbCategoryService.getCategoryName(bsbExpertQu.getTax());
		String topic = bsbCategoryService.getCategoryName(bsbExpertQu.getTopic());
		Integer firmId = bsbExpertQu.getFirmId();
		BsbFirm bsbFirmByAccount = BsbFirmService.getBsbFirmByAccount(firmId);
		if (bsbFirmByAccount!=null) {
			model.addAttribute("firmName", bsbFirmByAccount.getName());
		}
		bsbExpertQu.setTrade(trade);
		bsbExpertQu.setTax(tax);
		bsbExpertQu.setTopic(topic);
		String userId = bsbUserService.getUserNameById(bsbExpertQu.getUserId());
		bsbExpertQu.setUserId(userId);
		List<BsbExpertVoice> voicelist = getVoiceList(uuid);
		model.addAttribute("voicelist", voicelist);
		model.addAttribute("bsbExpertQu", bsbExpertQu);
		return "/BsbExpertQu/view";
	}
}
